package com.cheng.example.geektime.designpatterns.j57.writeventbuself;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class EventBus {

    //创建个list存储观察者对象
    List<Object> list = new ArrayList<>();

    // 注册方法
    public void register(Object object) {
        list.add(object);
    }

    // 移除方法
    public void unregister(Object object) {
        list.remove(object);
    }

    // 发送信息方法
    public void post(Object post) {
        Class postClass = post.getClass();
        for (Object o : list) {
            Class aClass = o.getClass();
            Method[] methods = aClass.getDeclaredMethods();
            for (Method method : methods) {
                Annotation annotation = method.getAnnotation(Subscribe.class);
                if (annotation != null) {
                    Class[] paramTypes = method.getParameterTypes();
                    if (paramTypes == null) {
                        continue;
                    }
                    if (paramTypes.length == 1) {
                        Class typeClass = paramTypes[0];
                        if (postClass == typeClass || typeClass.isAssignableFrom(postClass)) {
                            Thread thread = new Thread(() -> {
                                try {
                                    method.invoke(o, post);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                } catch (InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            });
                            thread.start();
                        }
                    }
                }
            }
        }
    }

}
